package com.spring.sunflower.bottompanel;

import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.spring.sunflower.R;
import com.spring.sunflower.base.AppBaseFragment;
import com.spring.sunflower.constant.Constant;
import com.spring.sunflower.conversation.EmotionSubFragment;
import com.spring.sunflower.conversation.GiftFragment;
import com.spring.sunflower.conversation.TopicFragment;
import com.spring.sunflower.conversation.VoiceFragment;
import com.spring.sunflower.dialog.OnPermissionIntroClickListener;
import com.spring.sunflower.util.DisplayUtils;
import com.spring.sunflower.util.DoubleClickUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zejian
 * Time  16/1/6 下午5:26
 * Email shinezejian@163.com
 * Description:表情主界面
 */
public class EmotionMainFragment extends AppBaseFragment implements View.OnClickListener {

    //是否绑定当前Bar的编辑框的flag
    public static final String BIND_TO_EDITTEXT = "bind_to_edittext";
    //是否隐藏bar上的编辑框和发生按钮
    public static final String HIDE_BAR_EDITTEXT_AND_BTN = "hide bar's editText and btn";

    //当前被选中底部tab
    private static final String CURRENT_POSITION_FLAG = "CURRENT_POSITION_FLAG";
    private int CurrentPosition = 0;
    //底部水平tab
//    private RecyclerView recyclerview_horizontal;
    private HorizontalRecyclerviewAdapter horizontalRecyclerviewAdapter;
    //表情面板
    private EmotionKeyboard mEmotionKeyboard;

    public static EditText etEditInput;
    private ImageView bar_image_add_btn;
    private ImageView ivSend;
    private LinearLayout rl_editbar_bg;

    //需要绑定的内容view
    private View contentView;

    //不可横向滚动的ViewPager
//    private NoSmoothViewPager viewPager;

    //是否绑定当前Bar的编辑框,默认true,即绑定。
    //false,则表示绑定contentView,此时外部提供的contentView必定也是EditText
    private boolean isBindToBarEditText = true;

    //是否隐藏bar上的编辑框和发生按钮,默认不隐藏
    private boolean isHidenBarEditTextAndBtn = false;

    List<Fragment> fragments = new ArrayList<>();
    private ImageView ivVoice, ivImage, ivVideo, ivGift;
    public static ImageView ivEmoji;
    private TextView tvTopic;
    private EmotionSubFragment mEmotionSubFragment;
    private FragmentTransaction fragmentTransaction;
    private TopicFragment mTopicFragment;
    private Fragment mTempFragment;
    private VoiceFragment mVoiceFragment;
    private GiftFragment mGiftFragment;
    public static LinearLayout emotionLayout;

    public static EmotionMainFragment newInstance(Bundle arg) {
        EmotionMainFragment fragment = new EmotionMainFragment();
        Bundle bundle = new Bundle();
        boolean isFromHelp = arg.getBoolean(Constant.IS_FROM_HELP, false);
        bundle.putBoolean(Constant.IS_FROM_HELP, isFromHelp);
        fragment.setArguments(bundle);
        return fragment;
    }

    /**
     * 创建与Fragment对象关联的View视图时调用
     *
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main_emotion, container, false);

        isHidenBarEditTextAndBtn = false;
        //获取判断绑定对象的参数
        isBindToBarEditText = true;
        initView(rootView);
        emotionLayout = rootView.findViewById(R.id.ll_emotion_layout);
        mEmotionKeyboard = EmotionKeyboard.with(getActivity())
                .setEmotionView(emotionLayout)//绑定表情面板
                .bindToContent(contentView)//绑定内容view
                .bindToEditText(((EditText) rootView.findViewById(R.id.etEditInput)))//判断绑定那种EditView
                .bindToEmotionButton(ivEmoji)//绑定表情按钮
                .bindToTopicBtn(tvTopic)
                .bindToVoiceBtn(ivVoice)
                .bindToGiftBtn(ivGift)
                .build();
        initListener();
//        initFragments();
//        initDatas();

        //创建全局监听
        GlobalOnItemClickManagerUtils globalOnItemClickManager = GlobalOnItemClickManagerUtils.getInstance(getActivity());

//        if(isBindToBarEditText){
        //绑定当前Bar的编辑框
        globalOnItemClickManager.attachToEditText(etEditInput);

//        }else{
//            // false,则表示绑定contentView,此时外部提供的contentView必定也是EditText
//            globalOnItemClickManager.attachToEditText((EditText) contentView);
//            mEmotionKeyboard.bindToEditText((EditText)contentView);
//        }
        return rootView;
    }

    private void initFragments() {
        fragmentTransaction = getChildFragmentManager().beginTransaction();
        mEmotionSubFragment = new EmotionSubFragment();
        fragmentTransaction.replace(R.id.flContent, mEmotionSubFragment);
        fragmentTransaction.commit();
    }

    /**
     * 绑定内容view
     *
     * @param contentView
     * @return
     */
    public void bindToContentView(View contentView) {
        this.contentView = contentView;
    }

    /**
     * 初始化view控件
     */
    protected void initView(View rootView) {
        Bundle arguments = getArguments();
        boolean aBoolean = arguments.getBoolean(Constant.IS_FROM_HELP, false);
        LinearLayout llActionContainer = rootView.findViewById(R.id.llActionContainer);
        LinearLayout llTopContainer = rootView.findViewById(R.id.llTopContainer);
        ivVoice = rootView.findViewById(R.id.ivVoice);
        ivImage = rootView.findViewById(R.id.ivImage);
        ivVoice.setVisibility(View.GONE);
        ivImage.setVisibility(View.GONE);
        ivVideo = rootView.findViewById(R.id.ivVideo);
        ivEmoji = rootView.findViewById(R.id.ivEmoji);
        ivGift = rootView.findViewById(R.id.ivGift);
        tvTopic = rootView.findViewById(R.id.tvTopic);

//        viewPager = (NoSmoothViewPager) rootView.findViewById(R.id.vp_emotionview_layout);
//        recyclerview_horizontal = (RecyclerView) rootView.findViewById(R.id.recyclerview_horizontal);
        etEditInput = (EditText) rootView.findViewById(R.id.etEditInput);
        etEditInput.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                View decorView = getActivity().getWindow().getDecorView();
                decorView.getWindowVisibleDisplayFrame(rect);
                int screenHeight = decorView.getRootView().getHeight();
                int diffHeight = screenHeight - rect.bottom;
                boolean visible = diffHeight > screenHeight / 3;
                if (visible && listener != null) {
                    listener.sysKeyboardShow();
                }
            }
        });
        ivSend = (ImageView) rootView.findViewById(R.id.ivSend);
        if (aBoolean) {
            llActionContainer.setVisibility(View.GONE);
            tvTopic.setVisibility(View.GONE);
            etEditInput.setHint("请输入您的问题");
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) llTopContainer.getLayoutParams();
            layoutParams.setMargins(DisplayUtils.dip2px(mActivity,10),DisplayUtils.dip2px(mActivity,10),DisplayUtils.dip2px(mActivity,15),DisplayUtils.dip2px(mActivity,10));
            llTopContainer.setLayoutParams(layoutParams);
        } else {
            llActionContainer.setVisibility(View.VISIBLE);
            tvTopic.setVisibility(View.VISIBLE);
            etEditInput.setHint("想聊点什么？");
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) llTopContainer.getLayoutParams();
            layoutParams.setMargins(DisplayUtils.dip2px(mActivity,15),DisplayUtils.dip2px(mActivity,10),DisplayUtils.dip2px(mActivity,15),DisplayUtils.dip2px(mActivity,5));
            llTopContainer.setLayoutParams(layoutParams);
        }

    }

    /**
     * 初始化监听器
     */
    protected void initListener() {
        mEmotionKeyboard.setBottomKeyboardListener(new OnBottomKeyboardShowListener() {
            @Override
            public void bottomKeyboardShow() {
                if (listener != null) {
                    listener.bottomPanelShow();
                }
            }

            @Override
            public void bottomKeyboardHide() {
                if (listener != null) {
                    listener.bottomPanelHide();
                }
            }

            @Override
            public void emojiClick() {
//                switchFragment(Constant.CLICK_EMOJI);
                if (mEmotionSubFragment == null) {
                    mEmotionSubFragment = new EmotionSubFragment();
                }
                switchFragment(mEmotionSubFragment);
            }

            @Override
            public void topicClick() {
//                switchFragment(Constant.CLICK_TOPIC);
                if (mTopicFragment == null) {
                    mTopicFragment = new TopicFragment();
                }
                switchFragment(mTopicFragment);
                ivEmoji.setImageResource(R.drawable.ic_more_emoji);
            }

            @Override
            public void voiceClick() {
                showToast("该功能待开放...");
//                if (mVoiceFragment == null) {
//                    mVoiceFragment = new VoiceFragment();
//                }
//                switchFragment(mVoiceFragment);
                ivEmoji.setImageResource(R.drawable.ic_more_emoji);

            }

            @Override
            public void giftClick() {
                if (mGiftFragment == null) {
                    mGiftFragment = new GiftFragment();
                }
                switchFragment(mGiftFragment);
                ivEmoji.setImageResource(R.drawable.ic_more_emoji);
            }

            @Override
            public void emojiIcon(String type) {
                if ("emoji".equals(type)) {
                    ivEmoji.setImageResource(R.drawable.ic_more_emoji);
                } else {
                    ivEmoji.setImageResource(R.drawable.ic_keyboard);
                }
            }

            @Override
            public void showNeedChargeDialog() {
                showNeedCharge();
            }

        });
//        ivGift.setOnClickListener(this);
        ivImage.setOnClickListener(this);
        ivVideo.setOnClickListener(this);
        ivSend.setOnClickListener(this);
//        tvTopic.setOnClickListener(this);
    }

    private void switchFragment(Fragment fragment) {
        if (fragment != mTempFragment) {
            if (!fragment.isAdded()) {
                if (mTempFragment != null) {
                    getChildFragmentManager().beginTransaction().hide(mTempFragment)
                            .add(R.id.flContent, fragment).commit();
                } else {
                    getChildFragmentManager().beginTransaction().add(R.id.flContent, fragment).commit();
                }
            } else {
                getChildFragmentManager().beginTransaction().hide(mTempFragment)
                        .show(fragment).commit();
            }
            mTempFragment = fragment;
        }
    }

    private void switchFragment(String type) {
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        switch (type) {
            case Constant.CLICK_EMOJI:
                if (mEmotionSubFragment == null) {
                    mEmotionSubFragment = new EmotionSubFragment();
                }
                transaction.replace(R.id.flContent, mEmotionSubFragment);
                break;
            case Constant.CLICK_TOPIC:
                if (mTopicFragment == null) {
                    mTopicFragment = new TopicFragment();
                }
                transaction.replace(R.id.flContent, mTopicFragment);
                break;
            case Constant.CLICK_GIFT:

                break;
            case Constant.CLICK_VOICE:
                break;
        }
        transaction.commit();
    }

    /**
     * 数据操作,这里是测试数据，请自行更换数据
     */
    protected void initDatas() {
//        replaceFragment();
//        List<ImageModel> list = new ArrayList<>();
//        for (int i = 0; i < fragments.size(); i++) {
//            if (i == 0) {
//                ImageModel model1 = new ImageModel();
//                model1.icon = getResources().getDrawable(R.drawable.emoji_default);
//                model1.flag = "经典笑脸";
//                model1.isSelected = true;
//                list.add(model1);
//            } else {
//                ImageModel model = new ImageModel();
//                model.icon = getResources().getDrawable(R.drawable.ic_add);
//                model.flag = "其他笑脸" + i;
//                model.isSelected = false;
//                list.add(model);
//            }
//        }
//
//        //记录底部默认选中第一个
//        CurrentPosition = 0;
//        SPUtils.setSP(CURRENT_POSITION_FLAG, getActivity(), CurrentPosition);
////        SharedPreferencedUtils.setInteger(getActivity(), CURRENT_POSITION_FLAG, CurrentPosition);
//
//        //底部tab
//        horizontalRecyclerviewAdapter = new HorizontalRecyclerviewAdapter(getActivity(), list);
//        recyclerview_horizontal.setHasFixedSize(true);//使RecyclerView保持固定的大小,这样会提高RecyclerView的性能
//        recyclerview_horizontal.setAdapter(horizontalRecyclerviewAdapter);
//        recyclerview_horizontal.setLayoutManager(new GridLayoutManager(getActivity(), 1, GridLayoutManager.HORIZONTAL, false));
//        //初始化recyclerview_horizontal监听器
//        horizontalRecyclerviewAdapter.setOnClickItemListener(new HorizontalRecyclerviewAdapter.OnClickItemListener() {
//            @Override
//            public void onItemClick(View view, int position, List<ImageModel> datas) {
//                //获取先前被点击tab
//                int oldPosition = SPUtils.getIntSP(CURRENT_POSITION_FLAG, getActivity());
//                //修改背景颜色的标记
//                datas.get(oldPosition).isSelected = false;
//                //记录当前被选中tab下标
//                CurrentPosition = position;
//                datas.get(CurrentPosition).isSelected = true;
////                SharedPreferencedUtils.setInteger(getActivity(), CURRENT_POSITION_FLAG, CurrentPosition);
//                SPUtils.setSP(CURRENT_POSITION_FLAG, getActivity(), CurrentPosition);
//                //通知更新，这里我们选择性更新就行了
//                horizontalRecyclerviewAdapter.notifyItemChanged(oldPosition);
//                horizontalRecyclerviewAdapter.notifyItemChanged(CurrentPosition);
//                //viewpager界面切换
//                viewPager.setCurrentItem(position, false);
//            }
//
//            @Override
//            public void onItemLongClick(View view, int position, List<ImageModel> datas) {
//            }
//        });


    }

    private void replaceFragment() {
        //创建fragment的工厂类
        FragmentFactory factory = FragmentFactory.getSingleFactoryInstance();
        //创建修改实例
        EmotionComplateFragment f1 = (EmotionComplateFragment) factory.getFragment(EmotionUtils.EMOTION_CLASSIC_TYPE);
        EmotionVerticalFragment emotionVerticalFragment = new EmotionVerticalFragment(etEditInput);
        fragments.add(emotionVerticalFragment);
        Bundle b = null;
//        for (int i = 0; i < 7; i++) {
//            b = new Bundle();
//            b.putString("Interge", "Fragment-" + i);
//            Fragment1 fg = Fragment1.newInstance(Fragment1.class, b);
//            fragments.add(fg);
//        }

        NoHorizontalScrollerVPAdapter adapter = new NoHorizontalScrollerVPAdapter(getActivity().getSupportFragmentManager(), fragments);
//        viewPager.setAdapter(adapter);
    }


    /**
     * 是否拦截返回键操作，如果此时表情布局未隐藏，先隐藏表情布局
     *
     * @return true则隐藏表情布局，拦截返回键操作
     * false 则不拦截返回键操作
     */
    public boolean isInterceptBackPress() {
        return mEmotionKeyboard.interceptBackPress();
    }


    private OnBottomPanelShowListener listener;

    public void setOnBottomPanelShowListener(OnBottomPanelShowListener listener) {
        this.listener = listener;
    }

    @Override
    public void onClick(View v) {
        if (DoubleClickUtils.isFastClick()) return;
        switch (v.getId()) {
            case R.id.ivSend:
                String data = etEditInput.getText().toString().trim();
                if (!TextUtils.isEmpty(data)) {
                    if (listener != null) {
                        listener.sendClick(data);
                        etEditInput.setText("");
                    }
                } else {
                    showToast("请输入聊天内容");
                }
                break;
            case R.id.ivVideo:
                //如果没有弹过规则就弹规则
                boolean hasShow = getField(Constant.KEY_SHOW_VIDEO_RULE_DIALOG, false);
                if (!hasShow) {
                    showTipDialog( new OnPermissionIntroClickListener() {
                        @Override
                        public void onClickCancel() {

                        }

                        @Override
                        public void onClickOK() {
                            if (listener != null) {
                                listener.sendVideoChat();
                            }
                        }
                    });
                } else {
                    if (listener != null) {
                        listener.sendVideoChat();
                    }
                }
                break;
            case R.id.ivImage:
                showToast("该功能待开放...");
//                String price = getField(Constant.KEY_CHATTER_PRICE, "");
//                String money = getField(Constant.KEY_MONEY, "");
//                if (!TextUtils.isEmpty(price) && !TextUtils.isEmpty(money)) {
//                    if (Double.valueOf(price) > Double.valueOf(money)) {
//                        showNeedCharge();
//                        return;
//                    }
//                }
//                if (listener != null) {
//                    listener.sendImage();
//                }
                break;
        }
    }
}


